/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gameheartv2;

import java.net.*;
import java.io.*;
import java.util.Random;
import java.util.Vector;

public class Server implements Runnable {

    private ServerThread clients[] = new ServerThread[50];
    private ServerSocket server = null;
    private Thread thread = null;
    private int clientCount = 0;
    int entireSlot = 1;
    Vector<String> vTapTin;
    public Vector<Player> vPlayer;
    String sentMsg = "6 1 ";

    public Server(int port) {
        try {
            InetAddress ipAddress = InetAddress.getLocalHost();
            vTapTin = new Vector<String>();
            System.out.println("Binding to port " + port + ", please wait  ...");
            server = new ServerSocket(port, 0, ipAddress);
            System.out.println("Server started: " + server);
            start();
        } catch (IOException ioe) {
            System.out.println("Can not bind to port " + port + ": " + ioe.getMessage());
        }
        vPlayer = new Vector<Player>();
    }

    public void run() {
        while (thread != null) {
            try {
                System.out.println("Waiting for a client ...");
                addThread(server.accept());
            } catch (IOException ioe) {
                System.out.println("Server accept error: " + ioe);
                stop();
            }
        }
    }

    public void start() {
        if (thread == null) {
            thread = new Thread(this);
            thread.start();
        }
    }

    public void stop() {
        if (thread != null) {
            thread.stop();
            thread = null;
        }
    }

    private int findClient(int ID) {
        for (int i = 0; i < clientCount; i++) {
            if (clients[i].getID() == ID) {
                return i;
            }
        }
        return -1;
    }

    public synchronized void handle(int ID, String input) {

        System.out.println("message receive:" + input);
        if ((input == null ? "" != null : !input.equals("")) && input != null) {

            String[] parameterArray = input.split(" ");
            int code = Integer.parseInt(parameterArray[0]);
            String sentMsg;
            switch (code) {
                case 26:
                    String message = "25 " + vPlayer.size();
                    for (int i = 0; i < vPlayer.size(); i++) {
                        message = message + " " + vPlayer.elementAt(i).name + " " + vPlayer.elementAt(i).imagePath;
                    }
                    for (int i = 0; i < clientCount; i++) {
                        clients[i].send(message);
                        clients[findClient(ID)].send(message);
                    }


                    break;

                case 3:
                    if (vPlayer.size() < 4) {
                        String name = parameterArray[1];
                        String path = parameterArray[2];
                        Player player = new Player(name, path, 0);
                        player.ID4Host = vPlayer.size() + 1;
                        vPlayer.add(player);
                        clients[findClient(ID)].send("4 1 " + this.entireSlot);
                        this.entireSlot++;

                    } else {
                        clients[findClient(ID)].send("4 0");
                    }
                    break;
                case Define.START:
                    //Khoi tao bo bai
                    String[] so = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
                    String[] loai = {"0", "1", "2", "3"};
                    String[] soloai = new String[so.length * loai.length];

                    int n = 0;
                    for (int i = 0; i < so.length; i++) {
                        for (int j = 0; j < loai.length; j++) {
                            soloai[n] = so[i] + " " + loai[j];
                            n++;
                        }
                    }

                    //Xao bai
                    Random generator = new Random();

                    for (int i = 0; i < 10; i++) {
                        int random = generator.nextInt(52);
                        String[] temp = new String[soloai.length];

                        // copy tu 0 -> random ve cuoi mang temp
                        int k = temp.length - 1;
                        for (int j = 0; j < random; j++) {
                            temp[k] = soloai[j];
                            k--;
                        }

                        //copy tu random -> soloai.length ve dau mang temp
                        int y = 0;
                        for (int x = random; x < soloai.length; x++) {
                            temp[y] = soloai[x];
                            y++;
                        }
                        //luu lai ket qua vao mang soloai
                        System.arraycopy(temp, 0, soloai, 0, soloai.length);
                    }

                    //Chia bai
                    int playerID = 0;
                    int startPlayer = 0;
                    int start = 0;
                    int end = 13;

                    //tim xem thang nao co con 2 nhep thi cho no lam startPlayer
                    for (int t = 0; t < 52; t++) {
                        if (soloai[t].compareTo("0 1") == 0) {
                            startPlayer = t / 13;
                            break;
                        }
                    }

                    for (int x = 0; x < 4; x++) {
                        String baiDuocChia = "";
                        for (int i = start; i < end; i++) {
                            baiDuocChia += soloai[i] + " ";
                        }
                        try {
                            clients[playerID].send("6 " + startPlayer + " " + baiDuocChia);
                            start = end;
                            end += 13;
                            playerID++;
                        } catch (Exception ex) {
                            System.out.print("khong du nguoi");
                        }
                    }
                    //clients[0].send("6 1 12 0 3 0 3 1 3 2 3 3 4 0 4 1 4 2 4 3 5 0 5 1 5 2 5 3");
                    break;

//                     clients[1].send("6 1 4 2 9 2 2 0 3 1 6 3 3 3 1 3 11 1 12 0 9 1 1 2 8 1 4 1");
//                     clients[2].send("6 1 4 3 5 0 5 3 7 3 9 0 6 1 6 0 1 1 3 0 9 3 4 0 5 2 7 1 ");
//                     clients[3].send("6 1 6 2 8 2 12 1 0 0 11 0 10 2 3 2 7 0 8 0 11 3 10 1 12 2 12 3 ");
//                    break;

                case 7:
                    sentMsg = "8";
                    int nguoidanh = Integer.parseInt(parameterArray[3]);
                    int nguoiketiep = -1;
                    
                    //kiem tra nguoi ke tiep
                    if (nguoidanh < 3) {
                        nguoiketiep = nguoidanh + 1;
                    } else {
                        nguoiketiep = 1;
                    }

                    for (int i = 1; i < parameterArray.length; i++) {
                        sentMsg = sentMsg + " " + parameterArray[i];
                    }
                    sentMsg += " " + nguoiketiep;
                    
                    for (int i = 0; i < clientCount; i++) {
                        clients[i].send(sentMsg);
                    }
                    break;

                case Define.CHAT_MSG_SERVER: {
                    String name = parameterArray[1];
                    String message10 = "";
                    for (int i = 2; i < parameterArray.length; i++) {
                        message10 += parameterArray[i] + " ";
                    }

                    for (int i = 0; i < clientCount; i++) {
                        clients[i].send("12 " + name + " " + message10);
                    }
                    break;
                }

                case Define.HAI_MESSAGE: {
                    String message12 = input.substring(2);
                    for (int i = 0; i < clientCount; i++) {
                        clients[i].send("14 " + message12);
                    }
                    break;

                }
                case 15:

                    int nguoiDua = Integer.parseInt(parameterArray[1]);
                    nguoiDua = nguoiDua - 1;
                    int kieuDoi = Integer.parseInt(parameterArray[2]);
                    int nguoiNhan = 0;
                    switch (kieuDoi) {
                        case 1:
                            nguoiNhan = (nguoiDua + 1) % 4;
                            break;
                        case 2:
                            nguoiNhan = (nguoiDua + 3) % 4;
                            break;
                        case 3:
                            nguoiNhan = (nguoiDua + 2) % 4;
                            break;
                    }
                    nguoiNhan++;
                    String sntMsg = "16 " + nguoiNhan + " ";
                    for (int i = 0; i < 6; i++) {
                        sntMsg = sntMsg + parameterArray[i + 3] + " " + parameterArray[i + 4] + " ";
                        i++;
                    }
                    System.out.println(sntMsg);
                    this.vTapTin.add(sntMsg);
                    if (4 == vTapTin.size()) {
                        for (int i = 0; i < 4; i++) {
                            clients[Integer.parseInt(this.vTapTin.elementAt(i).split(" ")[1]) - 1].send(this.vTapTin.elementAt(i));
                            System.out.println("TO USER" + (Integer.parseInt(this.vTapTin.elementAt(i).split(" ")[1]) - 1) + "MSG" + this.vTapTin.elementAt(i));
                        }
                        break;
                    }

            }

        }
    }

    public synchronized void remove(int ID) {
        int pos = findClient(ID);
        if (pos >= 0) {
            ServerThread toTerminate = clients[pos];
            System.out.println("Removing client thread " + ID + " at " + pos);
            if (pos < clientCount - 1) {
                for (int i = pos + 1; i < clientCount; i++) {
                    clients[i - 1] = clients[i];
                }
            }
            clientCount--;
            vPlayer.remove(pos);
            try {
                toTerminate.close();
            } catch (IOException ioe) {
                System.out.println("Error closing thread: " + ioe);
            }
            toTerminate.stop();
        }
    }

    private void addThread(Socket socket) {
        if (clientCount < clients.length) {
            System.out.println("Client accepted: " + socket);
            clients[clientCount] = new ServerThread(this, socket);
            try {
                clients[clientCount].open();
                clients[clientCount].start();
                clientCount++;
            } catch (IOException ioe) {
                System.out.println("Error opening thread: " + ioe);
            }
        } else {
            System.out.println("Client refused: maximum " + clients.length + " reached.");
        }
    }

    public static void main(String args[]) {
        Server server = null;
        server = new Server(8999);
    }
}